/* MAIN.C file
 * 
 * Copyright (c) 2002-2005 STMicroelectronics
 */

#include "main.h"

uint8_t cnt20ms = 0;
uint8_t cnt1s = 0;
uint8_t cnt1min = 0;

uint8_t t1_cnt=0;
bool bling=FALSE;

void main()
{
	CLK_DeInit();
	CLK_HSICmd(ENABLE);
	CLK_HSIPrescalerConfig(CLK_PRESCALER_HSIDIV1);
	CLK_ClockSecuritySystemEnable();

	eeprom_init();  // 
	LED_init();     // 
	key_init();     // 
	heat_init();    //

#ifdef USE_DS18B20   // 使用DS18B20
	ds18b20_init();
#else
	ADC_init();
#endif

#ifdef USE_LCD       // 使用LCD段码屏
	LCD_Init();
#else
	seg_init();
#endif

#ifdef USE_UART
	UART_Init();
#endif

	InitTim4();          // Initial Timer4 for SEG Display
	InitTim1();          // Initial Timer1
	InitTim2();          // Initial Timer2 for Temperature Acquistion
	
	read_parameter();
	PIDInit(&sPID, temp_pid, 0, 0, temp_set);
	PowerUpShow();

	enableInterrupts();  // enable all interrupts
	
	while(1){
		
		if (t1==20){

			key_scan();

			t1 = 0;
			cnt20ms++;
			if (cnt20ms==50){
				cnt1s++;   // 1 second
				cnt20ms=0;	
			}
			if (cnt1s==60){
				cnt1min++;  // 1 min
				cnt1s=0;
				if (temp_shutdown){
					temp_shutdown--;
					if (temp_shutdown==0) {
						mode = MODE_SHUTDOWN;
						TIM2_Cmd(DISABLE);
						GPIO_WriteHigh(HEAT_PORT, HEAT);
						GPIO_WriteHigh(LED_PORT, LED_STATUS);
						GPIO_WriteHigh(LED_PORT, LED_POWER);
					}
				}
				cnt1min=cnt1min%1000;// 最大999分钟
			}

			if (t1_cnt==25) {
				bling = ~bling;
				t1_cnt = 0;
			}else{
				t1_cnt++;
			}
		}
	};
	
}

void delay(unsigned int t)
{
	unsigned int i,j;
	for(i=0; i<t;  i++)
    for(j=0; j<1; j++);
}

void PowerUpShow(void)
{

#ifdef USE_LCD
	LCD_ShowNum(0,8,8,8,0);
#else
	GPIO_WriteLow(SEG_PORT, SEG_SEL1);
	GPIO_WriteHigh(SEG_PORT, SEG_SEL2);
	GPIO_WriteHigh(SEG_PORT, SEG_SEL3);
	send_byte(0xFF);
	delay(10000);
	GPIO_WriteHigh(SEG_PORT, SEG_SEL1);
	GPIO_WriteLow(SEG_PORT, SEG_SEL2);
	GPIO_WriteHigh(SEG_PORT, SEG_SEL3);
	send_byte(0xFF);
	delay(10000);
	GPIO_WriteHigh(SEG_PORT, SEG_SEL1);
	GPIO_WriteHigh(SEG_PORT, SEG_SEL2);
	GPIO_WriteLow(SEG_PORT, SEG_SEL3);
	send_byte(0xFF);
	delay(10000);
	show_value = VERSION;  // 显示版本号
#endif

}

#ifdef USE_FULL_ASSERT

/**
  * @brief  Reports the name of the source file and the source line number
  *   where the assert_param error has occurred.
  * @param file: pointer to the source file name
  * @param line: assert_param error line source number
  * @retval : None
  */

void assert_failed(u8* file, u32 line)
{ 
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */

  /* Infinite loop */
  while (1)
  {
  }
  
}

#endif